// useUserManagement.ts
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Key } from 'ant-design-vue/es/table/interface'
import { useUserStore } from '@/stores/system/user'
import { storeToRefs } from 'pinia'
import type { User } from '@/types/api/system/user'
import type dayjs from 'dayjs'

/**
 * 用户管理页面逻辑钩子
 * @returns 用户管理状态和方法
 */
export default function useUserManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 使用状态管理 ------------
  const userStore = useUserStore()
  
  // 从store中提取响应式状态
  const { 
    loading, 
    submitLoading, 
    roleSubmitLoading,
    passwordSubmitLoading,
    formModalOpen,
    roleModalOpen,
    passwordModalOpen,
    userList,
    deptTreeData,
    roleOptions,
    roleListForTransfer,
    targetRoleIds,
    pagination,
    queryParams,
    dateRange,
    formData,
    formMode,
    formTitle
  } = storeToRefs(userStore)
  
  // ------------ 组件引用 ------------
  const formRef = ref<FormInstance>()
  
  // ------------ 本地状态 ------------
  const selectedRowKeys = ref<Key[]>([])
  
  // 选中行数量
  const selectedCount = computed(() => selectedRowKeys.value.length || 0)
  
  // ------------ 错误处理状态 ------------
  const loadError = ref(false)
  const errorMessage = ref('')
  
  // ------------ 计算属性 ------------
  const hasSelected = computed(() => selectedRowKeys.value.length > 0)
  
  // ------------ 表格交互方法 ------------
  /**
   * 表格选择行变化
   * @param keys 选中的键列表
   */
  const onSelectChange = (keys: Key[]) => {
    selectedRowKeys.value = keys
  }

  /**
   * 表格分页变更处理
   * @param pagination 分页信息
   */
  const handleTableChange = (pagination: any) => {
    const { current, pageSize } = pagination
    userStore.handlePageChange(current, pageSize)
  }
  
  // ------------ 搜索区域方法 ------------
  /**
   * 搜索
   */
  const handleSearch = () => {
    userStore.fetchUserList()
  }

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    userStore.resetQuery()
  }
  
  /**
   * 处理日期范围变化
   */
  const handleDateRangeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
    dateRange.value = dates || undefined
  }
  
  // ------------ 表单操作方法 ------------
  /**
   * 添加用户
   */
  const handleAdd = () => {
    userStore.openFormModal()
  }

  /**
   * 编辑用户
   * @param id 用户ID
   */
  const handleEdit = (id: string) => {
    userStore.openFormModal(id)
  }

  /**
   * 表单提交
   */
  const handleSubmit = async () => {
    try {
      await formRef.value?.validate()
      userStore.submitForm()
    } catch (error) {
      // 表单验证失败，无需处理
      console.error('表单验证失败:', error)
    }
  }
  
  // ------------ 删除操作方法 ------------
  /**
   * 删除用户
   * @param id 用户ID
   */
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: t('common.confirm'),
      content: t('user.deleteConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        await userStore.removeUsers([id])
      }
    })
  }

  /**
   * 批量删除
   */
  const handleBatchDelete = () => {
    if (selectedRowKeys.value.length === 0) {
      return
    }
    Modal.confirm({
      title: t('common.confirm'),
      content: t('user.batchDeleteConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        const success = await userStore.removeUsers(selectedRowKeys.value as string[])
        if (success) {
          selectedRowKeys.value = []
        }
      }
    })
  }
  
  // ------------ 状态管理方法 ------------
  /**
   * 修改用户状态
   * @param id 用户ID
   * @param status 状态值
   */
  const handleStatusChange = (id: string, status: number) => {
    userStore.changeStatus(id, status as 0 | 1)
  }
  
  // ------------ 特殊业务方法 ------------
  /**
   * 导出用户
   */
  const handleExport = async () => {
    // TODO: 实现导出功能
  }
  
  /**
   * 分配角色
   * @param record 用户记录
   */
  const handleAssignRoles = async (record: User) => {
    targetRoleIds.value = record.roles ? record.roles.map(role => role.id) : []
    userStore.currentId = record.id
    roleModalOpen.value = true
  }

  /**
   * 提交角色分配
   */
  const handleSubmitRoles = () => {
    userStore.submitRoles()
  }

  /**
   * 重置密码
   * @param record 用户记录
   */
  const handleResetPassword = (record: User) => {
    userStore.currentId = record.id
    // 确保密码表单字段被清空
    Object.assign(userStore.passwordForm, {
      newPassword: '',
      confirmPassword: ''
    })
    passwordModalOpen.value = true
  }

  /**
   * 提交重置密码
   */
  const handleSubmitResetPassword = async () => {
    try {
      const password = userStore.passwordForm.newPassword
      if (!password) {
        return
      }
      await userStore.resetPassword(password)
      // 重置成功后显示提示
      Modal.success({ 
        title: t('common.success'),
        content: t('user.resetPasswordSuccess')
      })
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  }
  
  /**
   * 获取用户列表
   */
  const fetchUserList = async () => {
    try {
      // 重置错误状态
      loadError.value = false
      errorMessage.value = ''
      
      await userStore.fetchUserList()
      
      // 检查数据是否为空
      if (userList.value.length === 0) {
        errorMessage.value = t('user.emptyData')
      }
      
      return userList.value
    } catch (error: any) {
      loadError.value = true
      errorMessage.value = error?.message || t('user.loadFailed')
      return Promise.reject(error)
    }
  }
  
  // ------------ 初始化 ------------
  onMounted(() => {
    // 初始化数据
    userStore.fetchUserList()
    userStore.fetchDeptTree()
    userStore.fetchRoleList()
  })
  
  // ------------ 返回结果 ------------
  return {
    // 状态数据
    loading,
    submitLoading,
    roleSubmitLoading,
    passwordSubmitLoading,
    formModalOpen,
    roleModalOpen,
    passwordModalOpen,
    userList,
    deptTreeData,
    roleOptions,
    roleListForTransfer,
    targetRoleIds,
    selectedRowKeys,
    selectedCount,
    dateRange,
    pagination,
    queryParams,
    formData,
    formMode,
    formTitle,
    formRef,
    hasSelected,
    passwordForm: userStore.passwordForm,
    
    // 表格交互方法
    onSelectChange,
    handleTableChange,
    
    // 搜索区域方法
    handleSearch,
    handleReset,
    handleDateRangeChange,
    
    // 表单操作方法
    handleAdd,
    handleEdit,
    handleSubmit,
    
    // 删除操作方法
    handleDelete,
    handleBatchDelete,
    
    // 状态管理方法
    handleStatusChange,
    
    // 特殊业务方法
    handleExport,
    handleAssignRoles,
    handleSubmitRoles,
    handleResetPassword,
    handleSubmitResetPassword,
    
    // 数据获取方法
    fetchUserList,
    
    // 错误处理状态
    loadError,
    errorMessage
  }
} 